package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Controller(value = "appMCourseController")
@RequestMapping(value = "/app/m/course")
public class CourseController extends BaseController {

    @Resource(name = "courseServiceImpl")
    private CourseService courseService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "recordServiceImpl")
    private RecordService recordService;
    @Resource(name= "categoryServiceImpl")
    private CategoryService categoryService;
    @Resource(name = "courseTradeServiceImpl")
    private CourseTradeService courseTradeService;
    @Resource(name = "snServiceImpl")
    private SnService snService;

    /**
     * 删除视频
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage delete(long id, String reason) {
        try {
            Record record = new Record();
            Member member = memberService.getCurrentByToken();
            if(member != null) {
                record.setUsername(member.getUsername());
            }
            Course course = courseService.find(id);
            if(course != null) {
                record.setTitle(course.getTitle());
                record.setCourseId(course.getId());
            }
            if(reason != null || !reason.isEmpty()) {
                record.setReason(reason);
            }
            record.setStatus(Record.Status.reviewing);
            recordService.save(record);
            return JsonMessage.success("提交审核中");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 发布预告
     * @param course
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage add(Course course, Long categoryId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Category category = categoryService.find(categoryId);
            if(category != null) {
                course.setCategory(category);
            }
            if(course.getPrice() == null) {
                course.setPrice(BigDecimal.ZERO);
            }
            course.setDatePattern(DateUtils.long2Date(course.getPubdate()*1000));
            course.setMember(member);
            course.setType(Course.Type.trailer);
            course.setCourseType(Course.CourseType.nolive);
            course.setPassword(course.getPassword());
            course.setIsTop(false);
            course.setHotSearch(false);
            courseService.save(course);
            return JsonMessage.success(course.getId());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 编辑预告
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage edit(Course course, Long categoryId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Category category = categoryService.find(categoryId);
            if(category != null) {
                course.setCategory(category);
            }
            if(!course.getCharge()) {
                course.setPrice(BigDecimal.ZERO);
                course.setPassword(null);
            } else {
                if (course.getPrice() == null || course.getPrice().compareTo(BigDecimal.ZERO) == 0) {
                    return JsonMessage.error("价格不能小于0");
                }
            }
            course.setDatePattern(DateUtils.long2Date(course.getPubdate()*1000));
            courseService.update(course,  "type", "member", "courseType", "isTop", "hotSearch", "live");
            return JsonMessage.success("编辑成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 我的预告列表(老师)
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage list(Pageable pageable) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if(teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Page<Course> page = courseService.findTrailerPage(pageable, teacher);
            return JsonMessage.success(
                    "totalPage", page.getTotalPages(),
                    "pageNumber", page.getPageNumber(),
                    "pageSize", page.getPageSize(),
                    "total", page.getTotal(),
                    "content", JsonMessage.optimiseObj(page.getContent(), "applyCount","charge", "title", "id", "imageURL","introduction",
                            "createDateF", "pubdate", "price", "member.id", "member.name", "member.avator", "member.username"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 课程详情
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage detail(Long courseId) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if(teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Course course = courseService.find(courseId);
            if (course == null) {
                return JsonMessage.error("课程已下架");
            }
            return JsonMessage.success(JsonMessage.optimiseObj(course, "courseType", "applyCount", "title", "pubdate", "id", "introduction", "imageURL", "price",
                    "charge", "encrypt", "password", "category.id", "category.name", "live.hisWatchCount", "live.watchCount","live.videoURL", "member.name", "member.avator"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 删除预告
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/delete_trailer", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage delete_trailer(Long courseId) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            courseService.delete(courseId);
            return JsonMessage.success("删除成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 我的视频(分类id)
     * @param categoryId
     * @return
     */
    @RequestMapping(value = "/vedio_list", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage vedio_list(Long categoryId, Pageable pageable) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if(teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Category category = categoryService.find(categoryId);
            Page<Course> page = courseService.findVedioPageByCategoryId(pageable, category, Course.Type.course);
            return JsonMessage.success(
                    "totalPage", page.getTotalPages(),
                    "pageNumber", page.getPageNumber(),
                    "pageSize", page.getPageSize(),
                    "total", page.getTotal(),
                    "content", JsonMessage.optimiseObj(page.getContent(), "title", "id", "introduction", "imageURL", "createDate", "pubdate", "price"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 我的视频（分类id）
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/my_vedio", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage myVedio(Pageable pageable, Long categoryId) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if (teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Category category = categoryService.find(categoryId);
            if(category == null) {
                return JsonMessage.error("找不到该分类");
            }
            Page<Course> page = courseService.findVedioPage(pageable, teacher, Course.CourseType.finished, category);
            return JsonMessage.success(
                    "totalPage", page.getTotalPages(),
                    "pageNumber", page.getPageNumber(),
                    "pageSize", page.getPageSize(),
                    "total", page.getTotal(),
                    "content", JsonMessage.optimiseObj(page.getContent(), "courseType", "applyCount","title", "id", "introduction", "imageURL", "member.avator", "member.name",
                            "pubdate", "live.hisWatchCount", "live.watchCount", "live.timeSpan", "encrypt", "password", "live.videoURL"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 已购买视频（根据分类id）
     * @param categoryId
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/buy_list", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage buyList(Long categoryId, Pageable pageable) {
        try {
            Member buyer = memberService.getCurrentByToken();
            if(buyer == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Page<CourseTrade> page = courseTradeService.findPaidCourseTrades(pageable, buyer, CourseTrade.PaymentStatus.paid, categoryId);
            return JsonMessage.success(
                    "totalPage", page.getTotalPages(),
                    "pageNumber", page.getPageNumber(),
                    "pageSize", page.getPageSize(),
                    "total", page.getTotal(),
                    "content", JsonMessage.optimiseObj(page.getContent(), "courseId","title", "imageURL", "pubdate"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 免费报名
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/no_apply", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage apply(Long courseId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            CourseTrade courseTrade = new CourseTrade();
            Course course = courseService.find(courseId);
            if(course != null) {
                courseTrade.setCourseId(course.getId());
                if(course.getMember() != null) {
                    courseTrade.setTeacherId(course.getMember().getId());
                }
                if(course.getMember().getAvator() != null) {
                    courseTrade.setTeacherAvator(course.getMember().getAvator());
                }
                if(course.getMember().getName() != null) {
                    courseTrade.setTeacherName(course.getMember().getName());
                }
                if(course.getCategory().getId() != null) {
                    courseTrade.setCategoryId(course.getCategory().getId());
                }
                if(course.getCategory().getName()!= null) {
                    courseTrade.setCategoryName(course.getCategory().getName());
                }
                if(course.getTitle() != null) {
                    courseTrade.setTitle(course.getTitle());
                }
                if(course.getImageURL() != null) {
                    courseTrade.setImageURL(course.getImageURL());
                }
                if(course.getIntroduction() != null) {
                    courseTrade.setIntroduction(course.getIntroduction());
                }
                if(course.getCharge() != null) {
                    courseTrade.setCharge(course.getCharge());
                }
                if(course.getEncrypt() != null) {
                    courseTrade.setEncrypt(course.getEncrypt());
                }
                if(course.getPassword() != null) {
                    courseTrade.setPassword(course.getPassword());
                }
                if(course.getPubdate() != null) {
                    courseTrade.setPubdate(course.getDatePattern());
                }
                if(course.getPrice() != null) {
                    courseTrade.setPrice(course.getPrice());
                }
                if (course.getApplyCount() != null) {
                    course.setApplyCount(course.getApplyCount()+1);
                }
                if(course.getCourseType() != null) {
                    if (course.getCourseType().equals(Course.CourseType.nolive)) {
                        courseTrade.setCourseType(CourseTrade.CourseType.nolive);
                    }
                    if (course.getCourseType().equals(Course.CourseType.live)) {
                        courseTrade.setCourseType(CourseTrade.CourseType.live);
                    }
                    if (course.getCourseType().equals(Course.CourseType.finished)) {
                        courseTrade.setCourseType(CourseTrade.CourseType.finished);
                    }
                }
                courseService.update(course);
            }
            courseTrade.setPubdate(course.getDatePattern());
            courseTrade.setBuyer(member);
            courseTrade.setHasReview(false);
            courseTrade.setPaymentStatus(CourseTrade.PaymentStatus.paid);
            courseTrade.setSn(snService.generate(Sn.Type.waste));
            courseTradeService.save(courseTrade);
            return JsonMessage.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 报名
     * @param courseId
     * @param note
     * @param phone
     * @param linkman
     * @return
     */
    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage apply(Long courseId, String note, String phone, String linkman) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (phone == null || phone.isEmpty()) {
                return JsonMessage.error("手机不能为空");
            }
            if (linkman == null || linkman.isEmpty()) {
                return JsonMessage.error("联系人不能为空");
            }
            CourseTrade courseTrade = new CourseTrade();
            Course course = courseService.find(courseId);
            if(course != null) {
                courseTrade.setCourseId(course.getId());
                if(course.getMember() != null) {
                    courseTrade.setTeacherId(course.getMember().getId());
                }
                if(course.getMember().getAvator() != null) {
                    courseTrade.setTeacherAvator(course.getMember().getAvator());
                }
                if(course.getMember().getName() != null) {
                    courseTrade.setTeacherName(course.getMember().getName());
                }
                if(course.getCategory().getId() != null) {
                    courseTrade.setCategoryId(course.getCategory().getId());
                }
                if(course.getCategory().getName()!= null) {
                    courseTrade.setCategoryName(course.getCategory().getName());
                }
                if(course.getTitle() != null) {
                    courseTrade.setTitle(course.getTitle());
                }
                if(course.getImageURL() != null) {
                    courseTrade.setImageURL(course.getImageURL());
                }
                if(course.getIntroduction() != null) {
                    courseTrade.setIntroduction(course.getIntroduction());
                }
                if(course.getCharge() != null) {
                    courseTrade.setCharge(course.getCharge());
                }
                if(course.getEncrypt() != null) {
                    courseTrade.setEncrypt(course.getEncrypt());
                }
                if(course.getPassword() != null) {
                    courseTrade.setPassword(course.getPassword());
                }
                if(course.getPubdate() != null) {
                    courseTrade.setPubdate(course.getDatePattern());
                }
                if(course.getPrice() != null) {
                    courseTrade.setPrice(course.getPrice());
                }
                if(course.getCourseType() != null) {
                    if (course.getCourseType().equals(Course.CourseType.nolive)) {
                        courseTrade.setCourseType(CourseTrade.CourseType.nolive);
                    }
                    if (course.getCourseType().equals(Course.CourseType.live)) {
                        courseTrade.setCourseType(CourseTrade.CourseType.live);
                    }
                    if (course.getCourseType().equals(Course.CourseType.finished)) {
                        courseTrade.setCourseType(CourseTrade.CourseType.finished);
                    }
                }
            }
            courseTrade.setPubdate(course.getDatePattern());
            courseTrade.setBuyer(member);
            courseTrade.setHasReview(false);
            courseTrade.setNote(note);
            courseTrade.setPhone(phone);
            courseTrade.setLinkman(linkman);
            courseTrade.setPaymentStatus(CourseTrade.PaymentStatus.unpaid);
            courseTrade.setSn(snService.generate(Sn.Type.waste));
            courseTradeService.save(courseTrade);
            return JsonMessage.success(
                    "sn", courseTrade.getSn()
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }



    /**
     * 判断用户是否购买预告
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/check_apply", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage checkApply(Long courseId) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Course course = courseService.find(courseId);
            if (course == null) {
                return JsonMessage.error("找不到该课程");
            }
            boolean isBuy = false;
            //当前用户是否报名
            long courseTradeCount = courseTradeService.findPaidCourse(course.getId(), member, CourseTrade.PaymentStatus.paid);
            //课程是否是该老师发布的
            if (member.getId().equals(course.getMember().getId()) || courseTradeCount >= 1) {
                isBuy = true;
            }
            return JsonMessage.success(
                    "isBuy", isBuy,
                    "course", JsonMessage.optimiseObj(course, "password", "encrypt")
                    );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }



}
